# coding=utf-8
# 代码文件：chapter11/ch11.2.py

import threading
import time
# psutil 模块可以获得系统进程信息

import psutil
import pywinauto
import xlwings as xw

last_message = None  # 保存最后的微信消息

dialogue_skill = None  # 保存客服话术数据

''' 根据问题返回答案函数 '''


def QA(q):
    for value in dialogue_skill:

        if value[0] == q:
            return value[1]


''' 读取客服话术数据函数 '''


def readData():
    global dialogue_skill
    app = xw.App(visible=False, add_book=False)
    excel_file = 'data/京东客服话术.xlsx'
    wb = app.books.open(excel_file)

    sheet1 = wb.sheets[0]
    rng = sheet1.range('A1').current_region

    dialogue_skill = rng.value

    print(dialogue_skill)

    wb.close()  # 关闭工作簿对象

    app.quit()  # 退出Excel应用程序


def thread_body():
    """ 线程体函数"""
    global last_message

    while True:
        for proc in psutil.process_iter():
            pinfo = proc.as_dict(attrs=['pid', 'name'])
            if 'WeChat.exe' == pinfo['name']:

                # 获得微信进程ID
                PID = pinfo['pid']
                try:
                    # 通过Win32模式访问微信
                    app = pywinauto.Application(backend='win32').connect(process=PID)
                    # 调用go函数开始工作
                    go(app)

                # 异常处理
                except:

                    # 发生异常，则通过UIA模式访问微信
                    app = pywinauto.Application(backend='uia').connect(process=PID)
                    # 调用go函数开始工作
                    go(app)

                    continue
        time.sleep(1)  # 休眠1秒继续执行


if __name__ == '__main__':
    readData()  # 读取话术数据

thread = threading.Thread(target=thread_body)  # 创建线程对象
thread.start()  # 启动线程

""" 微信工作函数  """


def go(app):
    win = app.window(title='微信')
    chat_list = win.child_window(control_type='List', title='消息')
    item = chat_list[-1]
    text = item.window_text().strip()
    print(text)
    answer = QA(text)
    if answer is not None:
        item.type_keys(answer)  # 输入回复消息
        time.sleep(1)
        pywinauto.keyboard.send_keys('%{S}')
